// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/common/base/bloom_filter.h>

#include <melon/hash.h>
#include <melon/random.h>
#include <gtest/gtest.h>
#include <unordered_set>

using namespace kumo::pollux;

class BloomFilterTest : public ::testing::Test {};

TEST_F(BloomFilterTest, basic) {
  constexpr int32_t kSize = 1024;
  BloomFilter bloom;
  bloom.reset(kSize);
  for (auto i = 0; i < kSize; ++i) {
    bloom.insert(melon::hasher<int32_t>()(i));
  }
  int32_t numFalsePositives = 0;
  for (auto i = 0; i < kSize; ++i) {
    EXPECT_TRUE(bloom.mayContain(melon::hasher<int32_t>()(i)));
    numFalsePositives += bloom.mayContain(melon::hasher<int32_t>()(i + kSize));
    numFalsePositives +=
        bloom.mayContain(melon::hasher<int32_t>()((i + kSize) * 123451));
  }
  EXPECT_GT(2, 100 * numFalsePositives / kSize);
}

TEST_F(BloomFilterTest, serialize) {
  constexpr int32_t kSize = 1024;
  BloomFilter bloom;
  bloom.reset(kSize);
  for (auto i = 0; i < kSize; ++i) {
    bloom.insert(melon::hasher<int32_t>()(i));
  }
  std::string data;
  data.resize(bloom.serializedSize());
  bloom.serialize(data.data());
  BloomFilter deserialized;
  deserialized.merge(data.data());
  for (auto i = 0; i < kSize; ++i) {
    EXPECT_TRUE(deserialized.mayContain(melon::hasher<int32_t>()(i)));
  }
  EXPECT_FALSE(
      deserialized.mayContain(melon::hasher<int32_t>()(kSize + 123451)));

  EXPECT_EQ(bloom.serializedSize(), deserialized.serializedSize());
}

TEST_F(BloomFilterTest, merge) {
  constexpr int32_t kSize = 10;
  BloomFilter bloom;
  bloom.reset(kSize);
  for (auto i = 0; i < kSize; ++i) {
    bloom.insert(melon::hasher<int32_t>()(i));
  }

  BloomFilter merge;
  merge.reset(kSize);
  for (auto i = kSize; i < kSize + kSize; i++) {
    merge.insert(melon::hasher<int32_t>()(i));
  }

  std::string data;
  data.resize(bloom.serializedSize());
  merge.serialize(data.data());

  bloom.merge(data.data());

  for (auto i = 0; i < kSize + kSize; ++i) {
    EXPECT_TRUE(bloom.mayContain(melon::hasher<int32_t>()(i)));
  }
  EXPECT_FALSE(bloom.mayContain(melon::hasher<int32_t>()(kSize + 123451)));

  EXPECT_EQ(bloom.serializedSize(), merge.serializedSize());
}
